/*******************************************************************************
 * Copyright (c) 2008 Sylvain Sicard.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Sylvain Sicard - initial API and implementation
 ******************************************************************************/
/*
 * Created on Feb 27, 2006
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package fr.jade.event.filters;

import java.util.HashSet;
import java.util.Set;

import fr.jade.event.Event;
import fr.jade.event.EventTag;
import fr.jade.fraclite.api.control.NoSuchAttributeException;
import fr.jade.util.JadeException;

public class TagEventFilterImpl extends BaseEventFilter {
  
  // attribute filterTags : "TAG1:TAG2,...."
  protected static final String filterTagsAttName = "filterTags";
  protected static final String tagSeparator      = ":";

  protected Set<EventTag>      filterTags        = new HashSet<EventTag>();

  public TagEventFilterImpl(){
    filterTags.add(EventTag.FAILURE);
  }
  
  // EventHandler
  public void handleEvent(Event e) throws JadeException {
    assert e != null;
    assert e.getEventHeader() != null;
    assert e.getEventBody() != null;
    
    log("filter :" + filterTags);
    log("event header :" + e.getEventHeader());
    if (e.getEventHeader().containsAll(filterTags)) {
      eh.handleEvent(e);
    }
    
  }

  // AttributeController
  @Override
  public String getAttribute(String name) throws NoSuchAttributeException {
    if (name.equals(filterTagsAttName)) {
      StringBuffer sb = new StringBuffer();
      for (EventTag tag : filterTags) {
        if (sb.length() > 0)
          sb.append(tagSeparator);
        sb.append(tag.toString());
      }
      return sb.toString();
    } else {
      return super.getAttribute(name);
    }
  }

  @Override
  public String[] listFcAtt() {
    HashSet<String> hs = new HashSet<String>();
    hs.add(filterTagsAttName);
    for (String att : super.listFc()){
      hs.add(att);
    }
    return (String[]) hs.toArray(new String[hs.size()]);
  }

  @Override
  public void setAttribute(String name, String value) throws NoSuchAttributeException {
    if (name.startsWith(filterTagsAttName)) {
      for (String tag : value.split(tagSeparator))
        filterTags.add(EventTag.valueOf(tag));
    } else {
      super.setAttribute(name, value);
    }
  }

}
